package com.gdou.crrp.common;

import com.gdou.crrp.entity.Reservation;
import com.gdou.crrp.repository.BillRepository;
import com.gdou.crrp.repository.ReservationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class TimeTask {

    @Autowired
    private ReservationRepository repository;

    @Autowired
    private BillRepository billRepository;

    /**
     * 每五分钟查询预约单，预约单下单时间超过5分钟还未付款就删除预约单
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void deleteTimeOutReservation(){
        List<Reservation> list = repository.findAllByStatus("待付款");
        Date time = new Date();
        for (Reservation res :
                list) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(res.getOrderTime());
            calendar.add(Calendar.MINUTE, 5);
            Date orderTime = calendar.getTime();
            if (time.after(orderTime)){
                repository.deleteById(res.getId());
                billRepository.deleteByBillId(res.getId());
            }
        }
    }
}
